/**
 * 事件管理器
 * 负责随机事件的生成、处理和管理
 */

import { EVENT_TEMPLATES } from '../config/event-templates.js';

export class EventManager {
    constructor(gameData, resourceManager, buildingManager) {
        this.gameData = gameData;
        this.resourceManager = resourceManager;
        this.buildingManager = buildingManager;
        this.eventIdCounter = 1;
    }

    /**
     * 生成随机事件
     * @returns {Object|null} 事件对象，如果没有生成则返回null
     */
    generateRandomEvent() {
        // 根据概率选择事件
        const random = Math.random();
        let cumulativeProbability = 0;

        for (const template of EVENT_TEMPLATES) {
            cumulativeProbability += template.probability;
            if (random <= cumulativeProbability) {
                const event = {
                    ...JSON.parse(JSON.stringify(template)), // 深拷贝
                    id: `${template.id}_${this.eventIdCounter++}`,
                    timestamp: Date.now(),
                    resolved: false
                };
                return event;
            }
        }

        return null;
    }

    /**
     * 添加事件到游戏数据
     * @param {Object} event - 事件对象
     */
    addEvent(event) {
        if (event) {
            this.gameData.events.push(event);
        }
    }

    /**
     * 获取当前活跃的事件
     * @returns {Array} 活跃事件列表
     */
    getActiveEvents() {
        return this.gameData.events.filter(e => !e.resolved);
    }

    /**
     * 获取事件
     * @param {string} eventId - 事件ID
     * @returns {Object|null} 事件对象
     */
    getEvent(eventId) {
        return this.gameData.events.find(e => e.id === eventId) || null;
    }

    /**
     * 处理事件选择
     * @param {string} eventId - 事件ID
     * @param {number} optionIndex - 选项索引
     * @returns {Object} {success: boolean, message: string}
     */
    handleEventChoice(eventId, optionIndex) {
        const event = this.getEvent(eventId);

        if (!event) {
            return { success: false, message: '事件不存在' };
        }

        if (event.resolved) {
            return { success: false, message: '事件已处理' };
        }

        if (!event.options || optionIndex < 0 || optionIndex >= event.options.length) {
            return { success: false, message: '无效的选项' };
        }

        const choice = event.options[optionIndex];

        // 检查需求
        if (choice.requirements) {
            if (!this.resourceManager.hasEnoughResources(choice.requirements)) {
                return { success: false, message: '资源不足' };
            }
        }

        // 扣除所需资源
        if (choice.requirements) {
            this.resourceManager.deductResources(choice.requirements);
        }

        // 给予奖励
        if (choice.rewards) {
            this.applyRewards(choice.rewards);
        }

        // 标记事件已解决
        event.resolved = true;
        event.resolvedAt = Date.now();
        event.choiceMade = optionIndex;

        return {
            success: true,
            message: `已选择: ${choice.text}`
        };
    }

    /**
     * 处理奖励事件
     * @param {string} eventId - 事件ID
     * @returns {Object} {success: boolean, message: string}
     */
    handleRewardEvent(eventId) {
        const event = this.getEvent(eventId);

        if (!event) {
            return { success: false, message: '事件不存在' };
        }

        if (event.resolved) {
            return { success: false, message: '事件已处理' };
        }

        if (event.type !== 'reward') {
            return { success: false, message: '不是奖励事件' };
        }

        // 给予奖励
        if (event.rewards) {
            this.applyRewards(event.rewards);
        }

        // 标记事件已解决
        event.resolved = true;
        event.resolvedAt = Date.now();

        return {
            success: true,
            message: `已领取奖励: ${event.name}`
        };
    }

    /**
     * 应用奖励
     * @param {Object} rewards - 奖励对象
     */
    applyRewards(rewards) {
        for (const [rewardType, value] of Object.entries(rewards)) {
            if (this.resourceManager.gameData.resources.hasOwnProperty(rewardType)) {
                // 资源奖励
                this.resourceManager.addResource(rewardType, value);
            } else if (rewardType === 'building_efficiency') {
                // 建筑效率奖励
                for (const [buildingId, efficiencyBonus] of Object.entries(value)) {
                    this.buildingManager.modifyBuildingEfficiency(buildingId, efficiencyBonus);
                }
            } else if (rewardType === 'morale') {
                // 士气奖励（暂时不处理，预留接口）
                console.log(`士气变化: ${value > 0 ? '+' : ''}${value}`);
            }
        }
    }

    /**
     * 清理已解决的旧事件
     * @param {number} maxAge - 最大保留时间（毫秒），默认24小时
     */
    cleanupOldEvents(maxAge = 24 * 60 * 60 * 1000) {
        const now = Date.now();
        this.gameData.events = this.gameData.events.filter(event => {
            if (event.resolved && event.resolvedAt) {
                return (now - event.resolvedAt) < maxAge;
            }
            return true; // 保留未解决的事件
        });
    }

    /**
     * 获取事件显示信息
     * @param {string} eventId - 事件ID
     * @returns {Object|null} 事件显示信息
     */
    getEventDisplayInfo(eventId) {
        const event = this.getEvent(eventId);

        if (!event) {
            return null;
        }

        const displayInfo = {
            ...event,
            optionsWithStatus: []
        };

        // 如果是选择事件，添加选项状态
        if (event.options) {
            displayInfo.optionsWithStatus = event.options.map(option => {
                const canAfford = option.requirements ?
                    this.resourceManager.hasEnoughResources(option.requirements) : true;

                return {
                    ...option,
                    canAfford: canAfford
                };
            });
        }

        return displayInfo;
    }

    /**
     * 获取所有活跃事件的显示信息
     * @returns {Array} 事件显示信息列表
     */
    getAllActiveEventsDisplayInfo() {
        const activeEvents = this.getActiveEvents();
        return activeEvents.map(event => this.getEventDisplayInfo(event.id));
    }
}
